import {Component, OnDestroy, OnInit} from '@angular/core';
import {FormBuilder} from '@angular/forms';
import {DatePipe} from '@angular/common';
import {Device} from '../../../entity/device.model';
// 报警级别、类别数据模型
import {TurbComponent} from '../../../entity/turbcomponent.model';
import {DataSourceService} from '../../../service/data-source/data-source.service';
// 列表数据模型
import {FaultCount} from '../../../entity/alarm/alarm-search.data';
import {AlarmService} from '../../../service/alarm/alarm.service';
import {DeviceAlarm} from '../../../entity/alarm/alarm.model';
import {DeviceCategoryEnum} from '../../common/device-tag-selector/device-category.enum';
import * as XLSX from 'xlsx';

@Component({
  selector: 'app-alarm-search',
  templateUrl: './alarm-search.component.html',
  styleUrls: ['./alarm-search.component.css'],
  providers: [DataSourceService]
})
export class AlarmSearchComponent implements OnInit, OnDestroy {
  public deviceCategories: DeviceCategoryEnum[] = [DeviceCategoryEnum.turbine, DeviceCategoryEnum.inverter];
  public alarmList: DeviceAlarm[] = [];
  public alarmListCache: DeviceAlarm[] = [];
  public aalarmList: DeviceAlarm[] = [];
  /**
   * 风机id集合
   *
   * @type @memberof AlarmSearchComponent
   */
  private turbineIds: number[] = [];
  public endTime = new Date();
  public startTime: Date = new Date(this.endTime.getTime() - 7200 * 1000);
  /**
   * 是否显示提示框
   *
   * @type {number}
   * @memberof AlarmSearchComponent
   */
  display: boolean = false;
  mes: string;

  /**
   * 查询时间间隔
   *
   * @type {number}
   * @memberof AlarmSearchComponent
   */
  public timeInterval: number;
  /**
   * 故障编码
   *
   * @memberof AlarmSearchComponent
   */
  public krCode: string;
  /**
   * 报警级别
   *
   * @memberof AlarmSearchComponent
   */
  public faultLevelId: number;
  /**
   * 故障描述模糊查询
   *
   * @memberof AlarmSearchComponent
   */
  public edDesc: string;
  /**
   *刚进页面是默认选择风机数量
   *默认:null 不做限制
   * 0不选择
   * @memberof AlarmSearchComponent
   */
  defaultChooseDeviceCount: number = 66;
  en: any;
  public active: number = 0;
  public isShowTime: boolean = false;
  /**
   * 故障统计数据集合
   * @type @memberof AlarmListComponent
   */
  public faultCountData: FaultCount[] = [];
  public faultCountList: FaultCount[] = [];
  public pages: number;

  // 故障类别数据集合
  public turbComponents: TurbComponent[] = [];

  /**
   * 故障描述模糊查询
   *
   * @memberof AlarmListComponent
   */
  totalRecords: number;
  sortO: number = -1;
  sortF = 'faultCount';
  sortFO: number = -1;
  sortFault = 'faultCode';
  subIndex = 0;
  cols: any[];
  /**
   * 报警描述变化定时器
   *
   * @type {*}
   * @memberof AlarmListComponent
   */
  timer: any;
  first = 0;
  firstHis = 0;
  rows = 20;

  constructor(
    private dataSource: DataSourceService,
    private fb: FormBuilder,
    private datePipe: DatePipe,
    private alarmService: AlarmService,
  ) {
  }


  ngOnInit(): void {
    console.log(this.startTime, this.endTime)
    this.cols = [
      {field: 'deviceName', header: '设备', width: '5%'},
      {field: 'modelName', header: '型号', width: '10%'},
      {field: 'GN', header: '点名', width: '15%'},
      {field: 'faultDesc', header: '描述', width: '15%'},
      {field: 'firstModule', header: '一级系统', width: '10%'},
      {field: 'secondModule', header: '二级系统', width: '10%'},
      {field: 'thirdModule', header: '三级系统', width: '10%'},
      {field: 'faultLevelName', header: '级别', width: '6%'},
      {field: 'multipleValue', header: '值', width: '14%'},
      {field: 'faultBeginTime', header: '开始时间', width: '10%'},
      {field: 'faultEndTime', header: '结束时间', width: '10%'}
    ];
    this.en = {
      firstDayOfWeek: 0,
      dayNames: ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'],
      dayNamesShort: ['日', '一', '二', '三', '四', '五', '六'],
      dayNamesMin: ['日', '一', '二', '三', '四', '五', '六'],
      monthNames: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
      monthNamesShort: ['一', '二', '三', '四', '五', '六', '七', '八', '九', '十', '十一', '十二'],
      today: '今天',
      clear: '清除'
    };
    this.dataSource.alarmDevice(this.turbineIds).subscribe(next => {
      this.resolving(next);
    });
  }

  ngOnDestroy(): void {
    if (this.dataSource != null) {
      this.dataSource.dispose();
    }
  }

  resolving(data: DeviceAlarm[]): void {
    data.forEach(d => {
      let flag = true;
      for (let i = 0, l = this.alarmListCache.length; i < l; i++) {
        let dd = this.alarmListCache[i]
        if (d.GN == dd.GN) {
          dd.faultLevelName = d.faultLevelName;
          dd.multipleValue = d.multipleValue;
          dd.faultBeginTime = d.faultBeginTime;
          dd.faultEndTime = d.faultEndTime;
          flag = false;
          break;
        }
      }
      if (flag) {
        this.alarmListCache.unshift(d);
      }
    });
    this.alarmList = [];
    for (let i = 0, l = this.alarmListCache.length; i < l; i++) {
      let dd = this.alarmListCache[i];
      if (this.krCode && this.edDesc) {
        if ((dd.krCode.indexOf(this.krCode) > -1) && (dd.faultDesc.indexOf(this.edDesc) > -1)) {
          this.alarmList.push(dd);
        }
      } else if (this.krCode) {
        if (dd.krCode.indexOf(this.krCode) > -1) {
          this.alarmList.push(dd);
        }
      } else if (this.faultLevelId) {
        if (dd.faultLevelId == this.faultLevelId) {
          this.alarmList.push(dd);
        }
      } else if (this.edDesc) {
        if (dd.faultDesc.indexOf(this.edDesc) > -1) {
          this.alarmList.push(dd);
        }
      } else {
        this.alarmList.push(dd);
      }
    }
  }

  /**
   * 得到选中风场风机集合
   *
   * @type {Device[]}@memberof TurbineDataListComponent
   */

  onSelectedDevicesChange(ev: Device[]) {
    this.turbineIds = [];
    this.turbineIds.push(...ev.map(o => o.deviceId));
    this.turbineIds = this.turbineIds;
    clearTimeout(this.subIndex);
    this.subIndex = setTimeout(() => {
      this.dataSource.sendDeviceAlarmMessage(this.turbineIds);
    }, 2000);
  }

  exportAlarmData() {
    let str = `<thead>
      <tr>
        <th>风场名称</th>
        <th>设备</th>
        <th>描述</th>
        <th>一级系统</th>
        <th>二级系统</th>
        <th>三级系统</th>
        <th>内容</th>
        <th>开始时间</th>
        <th>结束时间</th>
      </tr>
    </thead>
    <tbody>`;
    this.aalarmList.forEach(row => {
      str += `<tr >
          <td>${row.farmName}</td>
            <td>${row.deviceName}</td>
            <td>${row.faultDesc}</td>
            <td>${row.firstModule}</td>
            <td>${row.secondModule}</td>
            <td>${row.thirdModule}</td>
            <td>${row.faultLevelName}</td>
            <td>${row.faultBeginTime}</td>
            <td>${row.faultEndTime}</td>
      </tr>`;
    })
    str += `</tbody>
  `;

    const elemTable = document.createElement('table');
    elemTable.innerHTML = str;
    const wb: XLSX.WorkBook = XLSX.utils.book_new();
    let ws = XLSX.utils.table_to_sheet(elemTable, {raw: true});
    XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');

    /* save to file */
    XLSX.writeFile(wb, '历史报警.xlsx');
  }

  apChange() {
    console.log('apchange', this.faultLevelId)
  }

  queryAlarm() {
    if (this.turbineIds.length <= 0) {
      alert('请选择风机');
      return;
    }
    if (this.endTime > new Date()) {
      this.mes = `结束时间不能大于当前时间`;
      return this.display = true;
    }
    if (this.startTime > this.endTime) {
      this.mes = `起始时间不能大于结束时间`;
      return this.display = true;
    }
    let time = this.endTime.getTime() - this.startTime.getTime() - 5000;    //毫秒数(5秒的延迟)
    let dayTime = time / 24 / 60 / 60 / 1000;             				    //天
    if (dayTime > this.timeInterval) {
      this.mes = `起始时间和结束时间不能超过${this.timeInterval}天`;
      return this.display = true;
    }
    const aalarmList = this.alarmService.getDeviceAAlarm(this.turbineIds, this.krCode, this.edDesc, this.faultLevelId, this.startTime.getTime() / 1000, this.endTime.getTime() / 1000);
    Promise.all([aalarmList])
      .then(res => {
        if (res[0]) {
          this.aalarmList = [];
          this.aalarmList = [...res[0]];
        } else {
          throw new Error('查询失败！');
        }
      }).catch(res => {
      console.log('获取报警历史错误:', res)
    });
  }

  onClickHeader(n: number) {
    this.active = n;
    if (this.active == 1) {
      this.isShowTime = true;
    } else {
      this.isShowTime = false;
    }
  }

  next() {
    this.first = this.first + this.rows;
  }

  prev() {
    this.first = this.first - this.rows;
  }

  reset() {
    this.first = 0;
  }

  isLastPage()
    :
    boolean {
    return this.first === (this.aalarmList.length - this.rows);
  }

  isFirstPage()
    :
    boolean {
    return this.first === 0;
  }
}
